package wikiArticleTypeMatch;

import java.io.*;
import java.util.*;

import zclTool.DelimitedReader;

public class ArticleType {

	static HashMap<Integer, String> wpid_name = new HashMap<Integer, String>();
	static HashMap<String, ArrayList<Integer>> guid_wpidlist = new HashMap<String, ArrayList<Integer>>();

	/**
	 * @param args
	 */
	public static void loadWpidName(String file) {
		try {
			DelimitedReader dr = new DelimitedReader(file);
			String []line = null;
			while((line = dr.read())!=null){
				wpid_name.put(Integer.parseInt(line[1]), line[2]);
			}
			dr.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void loadGuidWpidList(String file){
		try {
			DelimitedReader dr = new DelimitedReader(file);
			String []line = null;
			while((line = dr.read())!=null){
				String guid = line[0];
				int wpid = Integer.parseInt(line[1]);
				if(wpid_name.get(wpid)!=null){
					 ArrayList<Integer> wpids = guid_wpidlist.get(guid);
					 if(wpids==null){
						 wpids = new ArrayList<Integer>();
						 wpids.add(wpid);
						 guid_wpidlist.put(guid, wpids);
					 }else{
						 wpids.add(wpid);
					 }
				}
			}
			dr.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void parseTsv(String file,String writeToFile){
		try {
			DelimitedReader dr = new DelimitedReader(file);
			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(writeToFile),"utf-8");
			String []line = null;
			int ln=0;
			while((line = dr.read())!=null ){
				ln++;
				String guid = line[0];
				String type = line[1];
				ArrayList<Integer>wpids = guid_wpidlist.get(guid);
				if(wpids == null)continue;
				for(int wpid: wpids){
					String name = wpid_name.get(wpid);
					osw.write(wpid+"\t"+guid+"\t"+name+"\t"+type+"\t");
					for(int i=2;i<line.length;i++){
						osw.write(line[i]+"\t");
					}
					osw.write("\n");
				}
			}
			osw.close();
			dr.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println((new Date()).toString());
		loadWpidName(args[0]);
		loadGuidWpidList(args[1]);
		parseTsv(args[2],args[3]);
		System.out.println((new Date()).toString());
		System.out.println(guid_wpidlist.get("9202a8c04000641f8000000000003b60"));
	}

}
